package com.ds.lens.data.security;

import com.alibaba.fastjson.JSONObject;
import com.ds.lens.data.common.constant.Constants;
import com.ds.lens.data.common.util.HttpUtil;
import com.ds.lens.data.service.LensAuthService;
import com.ds.lens.data.vo.in.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.ds.lens.data.security.SecuritytConstants.SSO_TIMEOUT;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2019-11-06
 */
@Component("authentication" + SecuritytConstants.SSO)
public class SSOAuthentication implements Authentication {

    @Value("${lens.security.sso.host}")
    private String ssoHost;
    @Autowired
    LensAuthService lensAuthService;

    @Override
    public int authentication(HttpServletRequest request) {
        String sessionId = request.getHeader(SecuritytConstants.AUTHORIZATION);
        if (StringUtils.isEmpty(sessionId)) {
            return HttpServletResponse.SC_UNAUTHORIZED;
        }
        Header header = new BasicHeader(SecuritytConstants.AUTHORIZATION, sessionId);
        String url = SecuritytConstants.PREFIX + ssoHost + SecuritytConstants.VERIFY_API;
        ResponseEntity entity = HttpUtil.get(url, null, header, SSO_TIMEOUT);
        if (null == entity || entity.getStatusCode() != HttpStatus.OK) {
            return HttpServletResponse.SC_UNAUTHORIZED;
        }
        //获取用户数据
        JSONObject repObject = (JSONObject) entity.getBody();
        User user = repObject.toJavaObject(User.class);
        if (null != user && StringUtils.isNotEmpty(user.getUid()) && StringUtils.isNotEmpty(user.getUsername())) {
            user.setUserType(Constants.UserTypeEnum.SSO.getCode());
            //检查lens系统资源权限
            return lensAuthService.checkPermission(user, request.getRequestURI(), request) ? HttpServletResponse.SC_OK : HttpServletResponse.SC_FORBIDDEN;
        }
        return HttpServletResponse.SC_UNAUTHORIZED;
    }
}
